import yaml
import sqlite3
from sqlite3 import Cursor, Connection
import pymysql

def read_params(param_file):
    # 读取参数文件
    try:
        with open(param_file, "r", encoding="utf-8") as fi:
            params = yaml.safe_load(fi)
    except Exception as e:
        print(f'\n[Error] 读取配置文件异常: {e}\n')
    return params

def connect_db(db_config):
    if db_config['db_type'] == "sqlite":
        conn = sqlite3.connect(db_config['db_path'])
        cursor = conn.cursor()
    elif db_config['db_type'] == "mysql":
        conn = pymysql.connect(
            host=db_config['host'],
            user=db_config['user'],
            password=db_config['password'],
            database=db_config['database'],
            port=db_config['port'],
            charset='utf8'
        )
        cursor = conn.cursor()
        cursor.execute(f'CREATE DATABASE IF NOT EXISTS {db_config["db_database"]}')
        conn.select_db(db_config["db_database"])
    return conn, cursor

